package agenda

object SlottedEntry {
  val LOWEST_SLOT = 1
  val HIGHEST_SLOT = 24
  def isValidSlot(slot: Int) = (slot >= LOWEST_SLOT && slot <= HIGHEST_SLOT)
}

abstract class SlottedEntry(_agenda: Agenda, _day: Int, _subject: String)
  extends Entry(_agenda, _day, _subject) with Occupiable {

  def getFirstSlot(): Int = {
    var slot = SlottedEntry.LOWEST_SLOT
    while (!occupiesSlot(slot)) {
      slot += 1
    }
    return slot
  }

  def getLastSlot(): Int = {
    var slot = SlottedEntry.HIGHEST_SLOT
    while (!occupiesSlot(slot)) {
      slot -= 1
    }
    return slot
  }

  protected def occupiesSlot(slot: Int): Boolean

  override def overlapsWith(other: Entry): Boolean = {
    if (other == null)
      false
    if (this.day != other.day)
      false
    if (other.isInstanceOf[DayEvent])
      other.overlapsWith(this)
    if ((other.isInstanceOf[Occupiable]) && (!(other.asInstanceOf[Occupiable]).isOccupying))
      false
    val otherSlottedEntry: SlottedEntry = other.asInstanceOf[SlottedEntry];
    var slot = getFirstSlot();
    while ((slot <= SlottedEntry.HIGHEST_SLOT) && (!(this.occupiesSlot(slot) && otherSlottedEntry.occupiesSlot(slot))))
      slot = slot + 1;
    return slot <= SlottedEntry.HIGHEST_SLOT
  }
  
  override def getStartTime(): Long = {
	  super.getStartTime() + (getFirstSlot() - 1) * 60 * 60 * 1000
  }

  override def getEndTime(): Long = {
	  super.getStartTime() + getLastSlot() * 60 * 60 * 1000
  }
}